package com.jzg.jcptadmin.ui;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.adpter.ChooseResultAdapter;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.vo.ChooseResultData;
import com.jzg.jcptadmin.data.vo.UpDataResult;
import com.jzg.jcptadmin.presenter.ChooseResultPresenter;
import com.jzg.jcptadmin.view.MyErrorLayout;
import com.jzg.jcptadmin.viewinterface.ChooseResultInterface;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * author: guochen
 * date: 2016/11/8 15:20
 * email:
 */
public class ChooseResultActivity extends BaseActivity implements ChooseResultInterface, View.OnClickListener {
    @Bind(R.id.title_content)
    TextView titleContent;
    @Bind(R.id.title_return)
    ImageView titleReturn;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.lv_list)
    ListView lvList;
    @Bind(R.id.error_layout)
    MyErrorLayout errorLayout;
    private ChooseResultData chooseResultData;
    private List<String> noOptions = new ArrayList<>();//未选择项
    private ChooseResultAdapter chooseResultAdapter;
    private int userId;
    private ChooseResultPresenter chooseResultPresenter;
    private Map<String, String> resultMap = new LinkedHashMap<>();
    private EditText restlt_edit;
    private String carId;
    private ChooseResultData chooseResultDataCache;
    private UpDataResult upDataResult;
    private String isNewEighteen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_result);
        ButterKnife.bind(this);
        carId = getIntent().getStringExtra("carId");
        upDataResult = (UpDataResult) getIntent().getParcelableExtra("evaluateResult");
        isNewEighteen = getIntent().getStringExtra("isNewEighteen");
        tvRight.setText("确认");
        titleContent.setText("鉴定结果");
        initView();
        userId = appContext.getUser().getUserId();
        showDialog();
        chooseResultPresenter = new ChooseResultPresenter(DataManager.getInstance());
        chooseResultPresenter.attachView(this);
        chooseResultPresenter.LoadSourceData();
    }


    private void initView() {
        View view = View.inflate(this, R.layout.resultlist_foot, null);
        restlt_edit = (EditText) view.findViewById(R.id.detection_result_edit);
        lvList.addFooterView(view);
        errorLayout.setOnReloadClickLintener(new MyErrorLayout.ReloadClickLintener() {
            @Override
            public void onReload() {
                if (chooseResultPresenter != null) {
                    chooseResultPresenter.LoadSourceData();
                }
            }
        });

        //解决listView中嵌套EditText导致EditText不能滑动的问题
        restlt_edit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_UP:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });

    }

    private void initListener() {
        tvRight.setOnClickListener(this);
//        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if(datas.get(position).isSelect()){
//                    datas.get(position).setSelect(false);
//                }else{
//                    datas.get(position).setSelect(true);
//                }
//                chooseResultAdapter.notifyDataSetChanged();
//            }
//        });
    }

    private void initData() {

        chooseResultDataCache = (ChooseResultData) ACache.get(this).getAsObject(carId);
        if (chooseResultDataCache != null) { //有缓存
            restlt_edit.setText(chooseResultDataCache.getRemark());
            UpDataResult upDataResultCache = new UpDataResult();
            List<UpDataResult.SelectedItemBean> selectedItemBeens = new ArrayList<>();
            for (int j = 0; j < chooseResultDataCache.getData().size(); j++) {
                for (int n = 0; n < chooseResultDataCache.getData().get(j).getGroupValue().size(); n++) {
                    if (chooseResultDataCache.getData().get(j).getGroupValue().get(n).isSelect()) {
                        UpDataResult.SelectedItemBean selectedItemBean = new UpDataResult.SelectedItemBean();
                        selectedItemBean.setSelectedItemID(chooseResultDataCache.getData().get(j).getGroupValue().get(n).getItemID() + "");
                        selectedItemBean.setGroupID(chooseResultDataCache.getData().get(j).getGroupID() + "");
                        selectedItemBeens.add(selectedItemBean);
                    }
                }
            }
            upDataResultCache.setSelectedItem(selectedItemBeens);
            for (int i = 0; i < chooseResultData.getData().size(); i++) {
                for (int k = 0; k < chooseResultData.getData().get(i).getGroupValue().size(); k++) {
                    for (int j = 0; j < upDataResultCache.getSelectedItem().size(); j++) {
                        if (upDataResultCache.getSelectedItem().get(j).getGroupID().equals(chooseResultData.getData().get(i).getGroupID() + "")) {
                            if (upDataResultCache.getSelectedItem().get(j).getSelectedItemID().equals(chooseResultData.getData().get(i).getGroupValue().get(k).getItemID() + "")) {
                                chooseResultData.getData().get(i).getGroupValue().get(k).setSelect(true);
                            }
                        }

                    }

                }
            }

        } else if (this.upDataResult != null) {//审核驳回后回来评估结果有数据进行返回
            restlt_edit.setText(upDataResult.getRemark());
            for (int i = 0; i < chooseResultData.getData().size(); i++) {
                for (int k = 0; k < chooseResultData.getData().get(i).getGroupValue().size(); k++) {
                    for (int j = 0; j < this.upDataResult.getSelectedItem().size(); j++) {
                        if (this.upDataResult.getSelectedItem().get(j).getGroupID().equals(chooseResultData.getData().get(i).getGroupID() + "")) {
                            if (this.upDataResult.getSelectedItem().get(j).getSelectedItemID().equals(chooseResultData.getData().get(i).getGroupValue().get(k).getItemID() + "")) {
                                chooseResultData.getData().get(i).getGroupValue().get(k).setSelect(true);
                            }
                        }

                    }

                }
            }
        } else {

        }
        for (int i = 0; i < chooseResultData.getData().size(); i++) {
            resultMap.put(chooseResultData.getData().get(i).getGroupName(), "");
        }
        chooseResultAdapter = new ChooseResultAdapter(this, chooseResultData.getData());
        lvList.setAdapter(chooseResultAdapter);

    }

    @Override
    public void showDatas(ChooseResultData datas) {
        errorLayout.setVisibility(View.GONE);
        dismissDialog();
        if ("100".equals(datas.getStatus())) {
            this.chooseResultData = datas;
            initData();
            initListener();
        } else {
            MyToast.showLong(datas.getMsg());
        }
    }

    @Override
    public Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("tokenid", "6");
        params.put("userID", userId + "");
        params.put("isNewEighteen",isNewEighteen);
        Map<String, Object> maps = new HashMap<>();
        maps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(maps));
        return params;
    }

    @Override
    public void showError(String error) {
        dismissDialog();
        errorLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right:
                String results = "";
                noOptions.clear();
                initResultMap();
                for (String key : resultMap.keySet()) {
                    if (TextUtils.isEmpty(resultMap.get(key))) {
                        noOptions.add(key);
                    }
                    results = results + key + resultMap.get(key) + "；";
                    System.out.println("key=" + key + " value=" + resultMap.get(key));
                }
                if (noOptions.size() > 0) {
                    SweetAlertDialog sweetAlertDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
                    sweetAlertDialog.setCancelable(false);
                    sweetAlertDialog
                            .setTitleText("提示")
                            .setContentText(noOptions.toString() + "未选择鉴定结果,请选择")
                            .setConfirmText("知道了")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    sDialog.dismissWithAnimation();
                                }
                            })
                            .show();

                    return;
                }
                String editResult = restlt_edit.getText().toString().trim();
                if (TextUtils.isEmpty(editResult)) {
                    results = results.substring(0, results.length() - 1);
                } else {
                    if ("。；，！？.;?!".contains(editResult.substring(editResult.length() - 1))) {
                        results = results + editResult.substring(0, editResult.length() - 1);
                    } else {
                        results = results + restlt_edit.getText().toString().trim();
                    }
                }
                results = results + "。";
                EventBus.getDefault().post(results);
//                saveResult();
                chooseResultData.setRemark(restlt_edit.getText().toString().trim());
                ACache.get(this).put(carId, chooseResultData);
                EventBus.getDefault().post(initUpdataResult());
                finish();
                break;
            default:

                break;
        }
    }

    /**
     * 拼写上传的结果
     */
    private UpDataResult initUpdataResult() {
        UpDataResult upDataResult = new UpDataResult();
        upDataResult.setRemark(restlt_edit.getText().toString().trim());
        List<UpDataResult.SelectedItemBean> selectedItemBeens = new ArrayList<>();
        if (chooseResultData == null){
            return upDataResult;
        }
        for (int j = 0; j < chooseResultData.getData().size(); j++) {
            for (int n = 0; n < chooseResultData.getData().get(j).getGroupValue().size(); n++) {
                if (chooseResultData.getData().get(j).getGroupValue().get(n).isSelect()) {
                    UpDataResult.SelectedItemBean selectedItemBean = new UpDataResult.SelectedItemBean();
                    selectedItemBean.setSelectedItemID(chooseResultData.getData().get(j).getGroupValue().get(n).getItemID() + "");
                    selectedItemBean.setGroupID(chooseResultData.getData().get(j).getGroupID() + "");
                    selectedItemBeens.add(selectedItemBean);
                }
            }
        }
        upDataResult.setSelectedItem(selectedItemBeens);
        return upDataResult;
    }

    private void initResultMap() {
        resultMap.clear();
        for (int i = 0; i < chooseResultData.getData().size(); i++) {
            for (int k = 0; k < chooseResultData.getData().get(i).getGroupValue().size(); k++) {
                if (chooseResultData.getData().get(i).getGroupValue().get(k).isSelect()) {
                    resultMap.put(chooseResultData.getData().get(i).getGroupName(), chooseResultData.getData().get(i).getGroupValue().get(k).getItemValue());
                    break;
                } else {
                    resultMap.put(chooseResultData.getData().get(i).getGroupName(), "");
                }
            }
        }
    }

    @Override
    public void goBack(View v) {
        if (upDataResult != null && upDataResult.getSelectedItem().size() > 0) {
            EventBus.getDefault().post(initUpdataResult());
        }
        super.goBack(v);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (upDataResult != null && upDataResult.getSelectedItem().size() > 0) {
            EventBus.getDefault().post(initUpdataResult());
        }
        finish();
    }
}
